package com.infinit.selfhelp.common.net.interceptor

import com.drake.net.request.MediaConst
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import java.net.URLDecoder

class ContentTypeInterceptor  : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.method == "POST") {
            val body = request.body
            if (body != null) {
                val buff = Buffer()
                body.writeTo(buff)
                val json = buff.readUtf8()
                if (json.isNotBlank()) {
                    val newBody = parseInputToJSON(json).toString().toRequestBody(MediaConst.JSON)
                    request = request.newBuilder().post(newBody).build()
                }
            }
        }
        return chain.proceed(request)
    }

    private fun parseInputToJSON(input: String): JSONObject {
        // 解码 URL 编码的字符串
        val decodedInput = URLDecoder.decode(input, "UTF-8")

        // 将解码后的字符串分割为键值对
        val keyValuePairs = decodedInput.split("&").map { it.split("=") }

        // 构建 JSON 对象
        val jsonObject = JSONObject()
        keyValuePairs.forEach {
            if (it.size == 2) {
                val key = it[0]
                val value = it[1]
                jsonObject.put(key, value)
            }
        }

        return jsonObject
    }
}